{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random \n",
    "import numpy as np\n",
    "import time\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# make matplotlib figures appear inline\n",
    "%matplotlib inline \n",
    "\n",
    "# Some more magic so that the notebook will reload external python modules;\n",
    "# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X shape:  (47, 2)\n",
      "y shape:  (47, 1)\n",
      "First 10 examples from the dataset\n",
      "[[2.10400e+03 3.00000e+00 3.99900e+05]\n",
      " [1.60000e+03 3.00000e+00 3.29900e+05]\n",
      " [2.40000e+03 3.00000e+00 3.69000e+05]\n",
      " [1.41600e+03 2.00000e+00 2.32000e+05]\n",
      " [3.00000e+03 4.00000e+00 5.39900e+05]\n",
      " [1.98500e+03 4.00000e+00 2.99900e+05]\n",
      " [1.53400e+03 3.00000e+00 3.14900e+05]\n",
      " [1.42700e+03 3.00000e+00 1.98999e+05]\n",
      " [1.38000e+03 3.00000e+00 2.12000e+05]\n",
      " [1.49400e+03 3.00000e+00 2.42500e+05]]\n"
     ]
    }
   ],
   "source": [
    "# Load the data \n",
    "# The data is copied from the linear regression exercise of machine learning course from Andrew Ng\n",
    "# The file ex1data2.txt contains a training set of housing prices in Portland, Oregon. The first column is the \n",
    "# size of the house (in square feet), the second column is the number of bedrooms, \n",
    "# and the third column is the price of the house, which we want to predict.\n",
    "file_name = 'dataset/ex1data2.txt'\n",
    "with open(file_name, 'r') as f:\n",
    "    house_data = np.loadtxt(file_name, delimiter=',')\n",
    "    \n",
    "num_sample = house_data.shape[0] # number of all the samples\n",
    "X = house_data[:, :2]\n",
    "y = house_data[:, 2].reshape((-1,1))\n",
    "\n",
    "# Add intercept term or bias to X\n",
    "print('X shape: ', X.shape)\n",
    "print('y shape: ', y.shape)\n",
    "print('First 10 examples from the dataset')\n",
    "print(house_data[0:10, :])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 10 examples from the dataset\n",
      "[[ 0.13141542 -0.22609337  1.        ]\n",
      " [-0.5096407  -0.22609337  1.        ]\n",
      " [ 0.5079087  -0.22609337  1.        ]\n",
      " [-0.74367706 -1.5543919   1.        ]\n",
      " [ 1.27107075  1.10220517  1.        ]\n",
      " [-0.01994505  1.10220517  1.        ]\n",
      " [-0.59358852 -0.22609337  1.        ]\n",
      " [-0.72968575 -0.22609337  1.        ]\n",
      " [-0.78946678 -0.22609337  1.        ]\n",
      " [-0.64446599 -0.22609337  1.        ]]\n",
      "First 10 examples target\n",
      "[[399900.]\n",
      " [329900.]\n",
      " [369000.]\n",
      " [232000.]\n",
      " [539900.]\n",
      " [299900.]\n",
      " [314900.]\n",
      " [198999.]\n",
      " [212000.]\n",
      " [242500.]]\n"
     ]
    }
   ],
   "source": [
    "# Feature Normalization\n",
    "# By looking at the data, features differ by orders of magnitude\n",
    "# we need to perform feature scaling to make gradient descent converge much more quickly\n",
    "# Normalization: (x - mean) / std\n",
    "X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n",
    "# Add bias dimension\n",
    "X = np.hstack((X, np.ones((num_sample, 1))))\n",
    "print('First 10 examples from the dataset')\n",
    "print(X[0:10, :])\n",
    "print('First 10 examples target')\n",
    "print(y[0:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "iteration 0 / 1000 : loss 3082802778528.421875\n",
      "iteration 100 / 1000 : loss 96034162378.332947\n",
      "iteration 200 / 1000 : loss 96034162378.332977\n",
      "iteration 300 / 1000 : loss 96034162378.332977\n",
      "iteration 400 / 1000 : loss 96034162378.332977\n",
      "iteration 500 / 1000 : loss 96034162378.332977\n",
      "iteration 600 / 1000 : loss 96034162378.332977\n",
      "iteration 700 / 1000 : loss 96034162378.332977\n",
      "iteration 800 / 1000 : loss 96034162378.332977\n",
      "iteration 900 / 1000 : loss 96034162378.332977\n",
      "Traning time for BGD with vectorized version is 0.027220 \n",
      "\n",
      "BGD coefficient:\n",
      "[[109447.79646964]\n",
      " [ -6578.35485416]\n",
      " [340412.65957447]]\n",
      "iteration 0 / 3000 : loss 60204499976.354958\n",
      "iteration 300 / 3000 : loss 125093460.625119\n",
      "iteration 600 / 3000 : loss 1103992656.372859\n",
      "iteration 900 / 3000 : loss 7894993.529553\n",
      "iteration 1200 / 3000 : loss 1188550840.746390\n",
      "iteration 1500 / 3000 : loss 1878538418.457906\n",
      "iteration 1800 / 3000 : loss 19454657539.127789\n",
      "iteration 2100 / 3000 : loss 824715444.396756\n",
      "iteration 2400 / 3000 : loss 278147315.558614\n",
      "iteration 2700 / 3000 : loss 831367903.685933\n",
      "Traning time for SGD with vectorized version is 0.079531\n",
      "SGD coefficient:\n",
      "[[105344.64960098]\n",
      " [-14973.60325333]\n",
      " [346607.37571808]]\n"
     ]
    }
   ],
   "source": [
    "# Now train linear regression model by BGD and SGD algorithms \n",
    "# load our implementation\n",
    "from linreg import LinearRegression\n",
    "lr_bgd = LinearRegression()\n",
    "tic = time.time()\n",
    "losses_bgd = lr_bgd.train(X, y, method='bgd', learning_rate=1e-2, num_iters=1000, verbose=True)\n",
    "toc = time.time()\n",
    "print('Traning time for BGD with vectorized version is %f \\n' % (toc - tic))\n",
    "print(\"BGD coefficient:\")\n",
    "print(lr_bgd.W)\n",
    "\n",
    "lr_sgd = LinearRegression()\n",
    "tic = time.time()\n",
    "losses_sgd = lr_sgd.train(X, y, method='sgd', learning_rate=1e-2, num_iters=3000, verbose=True)\n",
    "toc = time.time()\n",
    "print('Traning time for SGD with vectorized version is %f' % (toc - tic))\n",
    "print(\"SGD coefficient:\")\n",
    "print(lr_sgd.W)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sklearn coefficient:\n",
      "[[109447.79646964  -6578.35485416      0.        ]]\n",
      "[340412.65957447]\n"
     ]
    }
   ],
   "source": [
    "# use sklearn to validate\n",
    "from sklearn import linear_model\n",
    "sklr = linear_model.LinearRegression()\n",
    "\n",
    "sklr.fit(X,y)\n",
    "print(\"sklearn coefficient:\")\n",
    "print(sklr.coef_)\n",
    "print(sklr.intercept_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
